package 线程同步.修改不安全的案例;

public class ToWithdrawMoney {
    public static void main(String[] args) {
        money money = new money("123456", 100);
        Thread thread = new Thread(new toMoney("123456", 50, money), "张三");
        Thread thread1 = new Thread(new toMoney("123456", 100, money), "张四");
        thread.setPriority(1);//设置优先级
        thread1.setPriority(10);
        thread.start();
        thread1.start();
    }
}

//模拟银行卡
class money {
    private String name;
    private long money;

    public money(String name, long money) {
        this.money = money;
        this.name = name;
    }

    public long getMoney() {
        return money;
    }

    public void setMoney(long money) {
        this.money = money;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

//模拟取钱
class toMoney implements Runnable {
    private String name;
    private long tomoney;
    money money;

    public toMoney(String name, long tomoney, 线程同步.修改不安全的案例.money money) {
        this.name = name;
        this.tomoney = tomoney;
        this.money = money;
    }

    @Override
    public void run() {
        To();
    }

    private void To() {
        synchronized (money) {
            if (money.getName().equals(name)) {
                if (money.getMoney() - tomoney >= 0) {
                    System.out.println("你的余额为：" + money.getMoney());
                    money.setMoney(money.getMoney() - tomoney);
                    System.out.println(Thread.currentThread().getName() + "-->取了" + tomoney);
                    System.out.println("你的余额为：" + money.getMoney());
                } else {
                    System.out.println("你的钱不够");
                }
            } else {
                System.out.println("你的账号错误");
            }
        }
    }
}